#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project    :icac2 
@File       :views.py
@Author     :wangfan13
@Date       :2021/5/26 17:45 
"""
import json
import hashlib
import xlsxwriter
import pandas as pd
from os.path import join, dirname

from django.http import FileResponse
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from apps.case.get_fields import get_rb_owner, get_cheat_owner, get_case_name_relationship, getpage
from apps.utils.mysql_utils import DBUtil_Dict
from apps.utils.response import response_result


@api_view(('POST',))
@permission_classes((IsAuthenticated,))
def download_excel(request):
    try:
        if request.method == 'POST' or 1 == 1:
            params = json.loads(request.body)
            dict_fields = {
                "ordercode": "订单SO",
                "settlecode": "结算案编号",
                "agent": "代理商名称",
                "reaptetimes": "重复次数",
                "realrefund": "实际金额",
                "shouldrefund": "应反金额",
                "productmodel": "产品型号",
                "orderproductotaltnum": "订单产品数量",
                "orderproductprice": "订单产品单价",
                "orderproducttotalprice": "订单产品总价",
                "casemode": "案件类型"}
            # re_dict = params['data']
            data = params['data']

            dbs = DBUtil_Dict()
            sql_query_case_by_policy_owner = "select * from (select ordercode,settlecode,agent,reaptetimes,realrefund,shouldrefund,'' productmodel," \
                                             "'' orderproductotaltnum,'' orderproductprice,'' orderproducttotalprice,0 casemode  FROM " \
                                             "case_relationship a left join RB_Settle_Check b on b.`ordercode`=cast(a.markkey as SIGNED) " \
                                             "where 1=1 " + get_rb_owner(data) + get_case_name_relationship(data) + \
                                             " union " \
                                             "select `订单SO` ordercode," \
                                             "`结算案编号` settlecode,`T1代理名称` agent,'' reaptetimes,'' realrefund,'' shouldrefund,'' productmodel," \
                                             "`产品数量` orderproductotaltnum,`产品单价` orderproductprice,`订单产品总价` orderproducttotalprice,1 casemode FROM" \
                                             " case_relationship a left join datacheat_1 b on b.`订单SO`=cast(a.markkey as SIGNED) where 1=1 " \
                                             + get_cheat_owner(data) + get_case_name_relationship(
                data) + ") a " + getpage(data)
            re_dict = dbs.get_all(sql_query_case_by_policy_owner)
            for item in re_dict:
                if item["casemode"] == 1:
                    item["casemode"] = '数据篡改'
                else:
                    item["casemode"] = '订单重复'
            print(re_dict)
            # 创建一个workbook,设置编码格式为utf8
            # workbook = xlwt.Workbook(encoding='utf-8')
            # # 创建一个 worksheet
            # worksheet = workbook.add_sheet('sheet')
            hash_md5 = hashlib.md5(str(re_dict).encode("utf8"))
            file_name = hash_md5.hexdigest() + '.xlsx'
            file_path = join(dirname(dirname(__file__)), "DownLoad", file_name)
            workbook = xlsxwriter.Workbook(file_path)
            # 2.新建一个worksheet
            worksheet = workbook.add_worksheet()

            if re_dict:
                for index, columns in enumerate(re_dict[0].keys()):
                    worksheet.write(0, index, dict_fields.get(columns, 1))
                for i in range(len(re_dict)):
                    for index, value in enumerate(re_dict[i].values()):
                        worksheet.write(i + 1, index, value)
            # hash_md5 = hashlib.md5(str(re_dict).encode("utf8"))
            # file_name = hash_md5.hexdigest() + '.xlsx'
            # file_path = join(dirname(dirname(__file__)), "DownLoad", file_name)
            # workbook.save(file_path)
            # workbook.
            workbook.close()
            file = open(file_path, 'rb')
            response = FileResponse(file)
            response['Content-Type'] = 'application/vnd.ms-excel'
            response['Content-Disposition'] = file_name
            return response
    except Exception as e:
        return response_result.res_faile(e)
